var ezqwBrowser = {
  isSetCommonSites:false,
  initialized:false,
    
  start: function() {
    if(!this.initialized){
		// initialization code
		this.initialized = true;
		this.strings = document.getElementById("ezqw-strings");

		var ezqwBox = document.getElementById("ezqw-box");
		var ezqwSplitter = document.getElementById("ezqw-splitter");  

		var xbrowser = document.getElementById("browser");
		xbrowser.appendChild(ezqwSplitter);
		xbrowser.appendChild(ezqwBox);
		ezqwSplitter.hidden = true;
		ezqwBox.hidden = true;
		this.browser(false);

		/* tried to monitor the search bar textbox event*/
		var searchbar = BrowserSearch.getSearchBar();
		if (searchbar) {
			searchbar.addEventListener("input", function(event) { ezqwBrowser.onSearchBarInput(event); }, false, true);
			//searchbar.addEventListener("focus", function(event) { ezqwBrowser.openFoxyBar(event); }, false, true);
		}
    }
  },

  onSearchBarInput:function(e){
    ezqwBrowser.openFoxyBar(e);

    //fill search keyword
    var searchBar = BrowserSearch.getSearchBar ();
    ezqwBrowser.setSearchKeyword(searchBar.value);
  },


  fillSearchBarText: function(text){
    var searchBar = BrowserSearch.getSearchBar ();
    searchBar.value = text;//window._content.document.location.protocol+"//"+window._content.document.location.host;
    //searchBar.focus();
    //searchBar._textbox.setSelectionRange(searchBar.value.length, searchBar.value.length); 
  },

  openFoxyBar:function(e){
    var ezqwBox = document.getElementById("ezqw-box");
    var ezqwSplitter = document.getElementById("ezqw-splitter");  
    if(ezqwSplitter.hidden==true){ //toggle to open
      ezqwSplitter.hidden = false;
      ezqwBox.hidden = false;
      gBrowserListener.start();
        setTimeout(function() { 
          //var urlPrePath = window._content.document.location.protocol+"//"+window._content.document.location.host;
          //if(urlPrePath && urlPrePath !=null) ezqwBrowser.setRelatedSites(urlPrePath);
          ezqwBrowser.setCommonSites();
        }, 1000);
    }

  },

  closeFoxyBar:function(e){
    var ezqwBox = document.getElementById("ezqw-box");
    var ezqwSplitter = document.getElementById("ezqw-splitter");  
    if(ezqwSplitter.hidden==false){ //toggle to close
      ezqwSplitter.hidden = true;
      ezqwBox.hidden = true;
      this.isSetCommonSites = false;
      gBrowserListener.stop();
    }
  },

  //toggle open/close ezqw browser
  toggle: function(e){
	var ezqwSplitter = document.getElementById("ezqw-splitter");  

	  if(ezqwSplitter.hidden==true){ //toggle to open
		this.openFoxyBar(e);
	  }else{ //toggle to close
		this.closeFoxyBar(e);
	  }
  },

  browser : function(isClose){
    var ezqwBox = document.getElementById("ezqw-box");
    var ezqwBar = document.getElementById("ezqw-bar");
  
    var ezqwBrowser = document.getElementById("ezqw-browser");
    if(isClose){
      try {
        ezqwBrowser.destroy();
        ezqwBox.removeChild(ezqwBrowser);
      }catch (e) {
      }
    }else{
      ezqwBrowser = document.createElement("browser");

      ezqwBrowser.setAttribute("id", "ezqw-browser");
      ezqwBrowser.setAttribute("name", "ezqw-browser");
      ezqwBrowser.setAttribute("flex", "1");
      ezqwBrowser.setAttribute("type", "content");
      ezqwBrowser.setAttribute("contextmenu", "contentAreaContextMenu");
      ezqwBrowser.setAttribute("oncontextmenu", "if (event.button == 2){document.getElementById('contentAreaContextMenu').setAttribute('ezqw', 'true')}; return contentAreaClick(event, false);");
      ezqwBrowser.setAttribute("onclick", "return contentAreaClick(event, false);");
      //ezqwBrowser.setAttribute("ondblclick", "return ezqwBrowser.toggle(event);");
      ezqwBrowser.setAttribute("src", "chrome://ezqw/content/index.html");
      //ezqwBrowser.setAttribute("homepage", FXF_SERVER_ROOT_URL);
      //ezqwBrowser.setAttribute("ondragdrop", "nsDragAndDrop.drop(event, ezqw.dNd);");
      ezqwBrowser.setAttribute("statustext", "Yi Zhi Qing Wa Helps You");
      
      //ezqwBox.appendChild(ezqwBrowser);
      ezqwBox.insertBefore(ezqwBrowser,ezqwBar);
    }
  },


  setGoogleSearchResultLinks:function(keyword,site,included)
  {

	  var url = FXF_GOOGLE_AJAX_SEARCH_API_URL + keyword ;
	  var regionid = "ezqw$-related$-link$-region$";
	  if(site && site != '') {
		  if(included == "Y") {
			  url= url + "+site%3A" + site;
		  }  else {
			  url= url + "+-site%3A" + site;
			  regionid = regionid+"included$";
		  }
	  }

	  if(fxf_pref_enablesignature) url = url + "&" + fxf_pref_signature;
	
      var ezqwSplitter = document.getElementById("ezqw-splitter");  
      if(ezqwSplitter.hidden==false){
        var ezqwBrowser = document.getElementById("ezqw-browser");
        if(ezqwBrowser && ezqwBrowser != null){
          var ezqwWindow = ezqwBrowser.contentWindow;
          var ezLinkRegion = ezqwWindow.document.getElementById(regionid);
          if(ezLinkRegion && ezLinkRegion != null){
			$.ajax({
				url: url,
				type: 'GET',
				dataType: 'json',
				timeout: 15000,
				error: function(){
					if(_DEBUG) consoleService.logStringMessage(' setGoogleSearchResultLinks error to search with url=['+url+']');
				},
				success: function(jd){
					// do something with json data
					if(jd['responseStatus'] == '200'){ //ok
						var results = jd['responseData']['results'];
			            var ezlinkStr = "";
						if(_DEBUG) consoleService.logStringMessage('==='+JSON.stringify(jd['responseData']['results']));
						for(var i=0;i < results.length; i++){
							var s = results[i];
							var surl = s['unescapedUrl'];
							if (fxf_pref_enablesignature) {
								if (surl.match(/[\?]/i)) surl += '&' + fxf_pref_signature;  else surl += '?' +fxf_pref_signature;
							}
							ezlinkStr = ezlinkStr + "<li class='link'><A id='"+s['visibleUrl']+"' href='"+surl+"' target='_blank'>"+(i+1)+". "+s['titleNoFormatting']+"</A></li>";
						}
			            ezLinkRegion.innerHTML = ezlinkStr;
					}

				},
				complete : function() { 
					if(_DEBUG) consoleService.logStringMessage("setGoogleSearchResultLinks complete google search url=["+url+"]");
				}

			});
		  }
        }
      }
  },

  /*
  * remove other site rss regions not in sites
  */
  removeOtherSiteRssFeedRegions:function(sites,regionid){
	  if(sites && sites.length > 0){
		if(_DEBUG) consoleService.logStringMessage("removeOtherSiteRssFeedRegions sites=["+JSON.stringify(sites)+"]");
		var ezqwSplitter = document.getElementById("ezqw-splitter");  
		var ezqwBrowser = document.getElementById("ezqw-browser");
		if (ezqwSplitter.hidden==false && ezqwBrowser && ezqwBrowser != null){
			var ezqwWindow = ezqwBrowser.contentWindow;
			var feedsRegion = ezqwWindow.document.getElementById(regionid);
			if(feedsRegion && feedsRegion != null && feedsRegion.hasChildNodes()){
				var siteFeedsRegsions = feedsRegion.childNodes;
				if(siteFeedsRegsions.length > sites.length){ 
					//only remove other site region when the old regions number exceeds the sites number
					for (var i = 0; i < siteFeedsRegsions.length; i++) {
						var siteFeedsRegsion = siteFeedsRegsions[i];
						if(siteFeedsRegsion && siteFeedsRegsion.hasAttribute("id")){
							var sfrid = siteFeedsRegsion.getAttribute("id");
							var sitesid = sfrid.replace("ezqw$-rss$-site$-feeds$-region$","");
							if(!contains(sites,sitesid)) {
								feedsRegion.removeChild(siteFeedsRegsion);
							}
						}
					}
				}
			}
		}
	  }
  },

  setSiteRssFeeds:function(site,regionid,pitemnum){

	if(site && site.rssPath && site.rssPath != FXF_NULL_STRING) {
	  var rssPath = site.rssPath;
	  var ezqwSplitter = document.getElementById("ezqw-splitter");  
      var ezqwBrowser = document.getElementById("ezqw-browser");
      if (ezqwSplitter.hidden==false && ezqwBrowser && ezqwBrowser != null){
        var ezqwWindow = ezqwBrowser.contentWindow;
		var sfrid = regionid+site.sid;
		var siteFeedsRegsion = ezqwWindow.document.getElementById(sfrid);

		if(!siteFeedsRegsion ){
		  var urlpara="";
		  if(fxf_pref_enablesignature) {
			  urlpara = fxf_pref_signature;
			  if (urlpara && urlpara !="" ) {
				if (rssPath.match(/[\?]/i)) {
					rssPath += '&' + urlpara;
				}else{ 
					rssPath += '?' +urlpara;
				}
			  }
		  }

          //1.========set sites by content category===========
          var feedsRegion = ezqwWindow.document.getElementById(regionid);
          if(feedsRegion && feedsRegion != null){
			$.ajax({
				url: rssPath,//'http://www.eetchina.com/rss/rss.xml',
				type: 'GET',
				dataType: 'xml',
				timeout: 15000,
				error: function(){
					if(_DEBUG) consoleService.logStringMessage(' setSiteRssFeeds Error loading XML document for site.url=['+site.url+'] rssPath=['+rssPath+"]");
				},
				success: function(xml){
					// do something with xml
	                var feedsStr = "";
					var currentFeed = new Feed(xml);

					var items = currentFeed.getItems("chrono");
					for(var i = 0; pitemnum > i && items.length > i; i++) {
						var item = items[i];
						var itemLabel = item.getTitle();
						itemLabel = (i+1) + ". " + itemLabel;
						var rsshref = item.getLink();
						if (urlpara && urlpara !="") {
							if (rsshref.match(/[\?]/i)) rsshref += '&' + urlpara;  else rsshref += '?' +urlpara;
						}
		                feedsStr = feedsStr + "<li class='link'><A id='"+item.getLink()+"' href='"+rsshref+"' target='_blank'>"+itemLabel+"</A></li>";
					}
					siteFeedsRegsion = ezqwWindow.document.createElement("div");
					siteFeedsRegsion.setAttribute("id", sfrid);
					siteFeedsRegsion.setAttribute("id", sfrid);
					feedsRegion.appendChild(siteFeedsRegsion);
					siteFeedsRegsion.innerHTML = feedsStr;
				},
				complete : function() { 
					if(_DEBUG) consoleService.logStringMessage("setSiteRssFeeds ajax complete get site feeds rssPath=["+rssPath+"]");
				}

			});
		  }
		}
	  }
	}
  },

  setRelatedSites: function(urlPrePath){
	  //0.============synchronize related sites ===============
	  foxySiteDB._syncSitesFromServer(urlPrePath,FXF_SITE_UPDATE_TIME);

	  var ezqwSplitter = document.getElementById("ezqw-splitter");  
      if(ezqwSplitter.hidden==false){
        var ezqwBrowser = document.getElementById("ezqw-browser");
        if(ezqwBrowser && ezqwBrowser != null){
          var ezqwWindow = ezqwBrowser.contentWindow;


          //2.========set sites by content category===========
          var siteRegion = ezqwWindow.document.getElementById("ezqw$-related$-site$-region$");
		  var contentRelatedSites ;
          if(siteRegion && siteRegion != null){
            contentRelatedSites = foxySiteDB.getRelatedSites(urlPrePath,"byContent");

            if(contentRelatedSites && contentRelatedSites != null && contentRelatedSites.length > 0){
              var siteStr = "";
              for (var i=0; i<contentRelatedSites.length; i++){
                var s = contentRelatedSites[i];
                siteStr = siteStr + "<li><A id='"+s.url+"' href='"+s.url+"' onClick='ezqwLink(this);' name='"+(!s.searchPath || s.searchPath==FXF_NULL_STRING?"":s.searchPath)+"' target='_blank'>"+s.name+"</A></li>";
              }
              var s = foxySiteDB._findSiteByUrl(urlPrePath);
              if(s && s.path){
				var catsids = s.path.split(",");
                siteRegion.innerHTML = siteStr+"&nbsp;&nbsp;<A href='"+CONFIG_SERVER_LIST_SITES_URL+"?wsgsid="+catsids[0]+"' target='_blank'>更多内容相关网址...</A>";
              }else{
                  siteRegion.innerHTML = siteStr;
              }
            }
			//else{
            //  siteRegion.innerHTML = "没有找到与"+urlPrePath+"内容相关的其他网址";
			//}

          }


          //3.========set sites by area category===========
          var siteRegion = ezqwWindow.document.getElementById("ezqw$-related$-area$-site$-region$");
		  var areaRelatedSites ;
          if(siteRegion && siteRegion != null){
            var areaRelatedSites = foxySiteDB.getRelatedSites(urlPrePath,"byArea");
            if(areaRelatedSites && areaRelatedSites != null && areaRelatedSites.length > 0){
              var siteStr = "";
              for (var i=0; i<areaRelatedSites.length; i++){
                var s = areaRelatedSites[i];
                siteStr = siteStr + "<li><A id='"+s.url+"' href='"+s.url+"' onClick='ezqwLink(this);' name='"+(!s.searchPath || s.searchPath==FXF_NULL_STRING?"":s.searchPath)+"' target='_blank'>"+s.name+"</A></li>";
              }
              var s = foxySiteDB._findSiteByUrl(urlPrePath);
              if(s && s.areaPath){
				var catsids = s.areaPath.split(",");
                siteRegion.innerHTML = siteStr+"&nbsp;&nbsp;<A href='"+CONFIG_SERVER_LIST_SITES_URL+"?argsid="+catsids[0]+"' target='_blank'>更多地区相关网址...</A>";
              }else{
                  siteRegion.innerHTML = siteStr;
              }
            }
			//else{
            //  siteRegion.innerHTML = "没有找到与"+urlPrePath+"地区相关的其他网址";
			//}
          }

		  var allRealtedSites;
		  if(contentRelatedSites){
				if(allRealtedSites)	allRealtedSites =  allRealtedSites.concat(contentRelatedSites);
				else allRealtedSites = contentRelatedSites;
		  } 		
		  if (areaRelatedSites){
				if(allRealtedSites)	allRealtedSites =  allRealtedSites.concat(areaRelatedSites);
				else allRealtedSites = areaRelatedSites;
		  }
		  allRealtedSites = unique(allRealtedSites);
		  if(allRealtedSites){
		  	for (var j = 0 ; j< allRealtedSites.length; j++){		  		
		  		this.setSiteRssFeeds(allRealtedSites[j],"ezqw$-rss$-feeds$-region$",fxf_pref_site_rss_feed_number);
		  	}
		  }
		  this.removeOtherSiteRssFeedRegions(allRealtedSites,"ezqw$-rss$-feeds$-region$");
        }
      }
  },
    
  setCommonSites: function(){
    if(this.isSetCommonSites == false){
      var ezqwBrowser = document.getElementById("ezqw-browser");
      if(ezqwBrowser && ezqwBrowser != null){
        var ezqwWindow = ezqwBrowser.contentWindow;
        var siteRegion = ezqwWindow.document.getElementById("ezqw$-common$-site$-region$");
        if(siteRegion && siteRegion != null){
          var sites = foxySiteDB.getCommonSites();
          var siteStr = "";
          if(sites && sites != null && sites.length > 0){
            for (var i=0; i<sites.length; i++){
              var s = sites[i];
              siteStr = siteStr + "<li><A id='"+s.url+"' href='"+s.url+"' onClick='ezqwLink(this);' name='"+(!s.searchPath || s.searchPath==FXF_NULL_STRING?"":s.searchPath)+"' target='_blank'>"+s.name+"</A></li>";
            }
            this.isSetCommonSites = true;
          }
          siteRegion.innerHTML = siteStr+"&nbsp;<A href='"+FXF_SERVER_USER_FAVORITE_LINK_URL+"' target='_blank'>定制常用网址...</A>";
        }
      }
    }
  },
    


  setSearchKeyword: function(keyword){
    var ezqwSplitter = document.getElementById("ezqw-splitter");  
    if(ezqwSplitter.hidden==false){
      var ezqwBrowser = document.getElementById("ezqw-browser");
      if(ezqwBrowser && ezqwBrowser != null){
        var ezqwWindow = ezqwBrowser.contentWindow;
        var searchKeyword = ezqwWindow.document.getElementById("ezqw$-search$-keyword$");
        if(searchKeyword && searchKeyword != null){
          //searchKeyword.value = encodeURI(keyword);
          searchKeyword.value = keyword;
        }
      }
    }  
  },

  /*
  * keywords is an array of keyword
  */
  setPageKeywords: function(keywords){
    var ezqwSplitter = document.getElementById("ezqw-splitter");  
    if(ezqwSplitter.hidden==false){
      var ezqwBrowser = document.getElementById("ezqw-browser");
      if(ezqwBrowser && ezqwBrowser != null){
        var ezqwWindow = ezqwBrowser.contentWindow;
        var pageKeywords = ezqwWindow.document.getElementById("ezqw$-page$-keywords$-region$");
        if(pageKeywords && pageKeywords != null){
          var keywordsStr = "";
          for (var i=0; i<keywords.length;i++){
            keywordsStr = keywordsStr + "&nbsp;<A href='http://www.google.com/?q="+keywords[i]+"' target=_blank>"+keywords[i]+"</A>";
          }
          pageKeywords.innerHTML = keywordsStr;
        }
      }
    }  
  },

  initContent:function(){
	  var ezqwSplitter = document.getElementById("ezqw-splitter");  
      if(ezqwSplitter.hidden==false){
        var browser = getBrowser().selectedBrowser;

		//set related sites
        var urlPrePath = browser.currentURI.prePath;
        if(urlPrePath == null){
          urlPrePath = window._content.document.location.protocol+"//"+window._content.document.location.host;
        }

        if(_DEBUG) consoleService.logStringMessage("initContent urlPrePath="+urlPrePath+" this.previousURL="+this.previousURL);
        if(urlPrePath && urlPrePath !=null && urlPrePath != this.previousURL){
          this.previousURL = urlPrePath;

		  //1.set the system sites' feeds /remove sites' feeds not of the current sites
		  var defSite = foxySiteDB._findSiteByUrl(FXF_SERVER_ROOT_URL);
  		  this.setSiteRssFeeds(defSite,"ezqw$-rss$-feeds$-region$-system$",fxf_pref_system_site_rss_feed_number);

          ezqwBrowser.setRelatedSites(urlPrePath);
        }
      }
  }

};


var gBrowserListener = {
	_DEBUG : true,
	consoleService: Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService),

    // This allows you to disable the listener
    // without having to remove the script file from
    // your xul overlay every time
    enabled: true,

    // Log info on each loaded/unloaded page to the console?
    dumpToConsole: false,
	initialized:false,

	//Store previous fired viewed URL on gBrowser
	previousURL: "about:blank",


	start: function(e){
		if(!this.initialized){
			// initialization code
			this.initialized = true;

			// Should we even bother?
			//if(!enabled) return;

			// Add our page listener(s)
			gBrowser.addEventListener("DOMContentLoaded", this.onContentLoaded, false);
			//gBrowser.addEventListener("load", this.onLoad, false);
			//gBrowser.addEventListener("TabOpen", function(e) { gBrowserListener.onTabOpen(e); }, true);
			gBrowser.addEventListener("TabSelect", this.onTabSelect, false);
			//gBrowser.addEventListener("pageshow", this.onPageShow, false);
			//gBrowser.addEventListener("pagehide", function(e) { gBrowserListener.onPageShow(e); }, true);
			gBrowser.addEventListener("mouseup", this.onMouseup, false);    
		}
	},

	stop: function(e){
		// When no longer needed
		gBrowser.removeEventListener("DOMContentLoaded", this.onContentLoaded , true);
		//gBrowser.removeEventListener("load", this.onLoad , true);
		gBrowser.removeEventListener("TabSelect", this.onTabSelect,false);
		//gBrowser.removeEventListener("pageshow", this.onPageShow,false);
		gBrowser.removeEventListener("mouseup", this.onMouseup,false);    
		this.initialized = false;
	},

    onLoad: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onLoad monitor gBrowser load event ok!");
        if(e.originalTarget instanceof HTMLDocument) {
            var doc = e.originalTarget;
            if(!doc.defaultView.frameElement) {
              // For top level documents only
			  ezqwBrowser.initContent();
            }
            setTimeout(function() { gBrowserListener.addLinksSignature()},2000);

            // Do something depending on the event type
			switch(e.type) {
                case "DOMContentLoaded": break;
                case "load": break;
                case "unload": break;
                default: break;
            } 
         }
    },


    onContentLoaded: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onContentLoaded monitor gBrowser onContentLoaded event ok!");
		ezqwBrowser.initContent();
        setTimeout(function() { gBrowserListener.addLinksSignature()},2000);
		var kw = gBrowserListener.getKeywords();
		if(_DEBUG) consoleService.logStringMessage("onTabSelect kw="+kw);
		if(kw && kw!=''){
            setTimeout(function() { 
				ezqwBrowser.setGoogleSearchResultLinks(kw,window._content.document.location.host,""),
				ezqwBrowser.setGoogleSearchResultLinks(kw,window._content.document.location.host,"Y")
				},1000);
		}
    },
    onTabOpen: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onTabOpen monitor gBrowser tabOpen event ok!");
    },

    onTabSelect: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onTabSelect monitor gBrowser tabSelect event ok!");
		ezqwBrowser.initContent();
        //setTimeout(function() { gBrowserListener.addLinksSignature()},2000);
		var kw = gBrowserListener.getKeywords();
		if(_DEBUG) consoleService.logStringMessage("onTabSelect kw="+kw);
		if(kw && kw!=''){
            setTimeout(function() { 
				ezqwBrowser.setGoogleSearchResultLinks(kw,window._content.document.location.host,""),
				ezqwBrowser.setGoogleSearchResultLinks(kw,window._content.document.location.host,"Y")
				},1000);
		}

    },

	onPageShow: function (e) {
		if(_DEBUG) consoleService.logStringMessage("onPageShow monitor gBrowser pageShow event ok!");
	},

	onPageHide: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onPageHide monitor gBrowser pageHide event ok!");
	},

	onMouseup: function(e) {
		var ezqwSplitter = document.getElementById("ezqw-splitter");  
		if(ezqwSplitter.hidden==false){
			if(_DEBUG) consoleService.logStringMessage("onMouseup monitor gBrowser Mouseup event ok!");

			//refer to http://www.quirksmode.org/dom/range_intro.html
			var sel =gBrowserListener._autocopy_getSelection();

			if(sel)  {
			  ezqwBrowser.openFoxyBar(e);
			  ezqwBrowser.setSearchKeyword(sel);
			  ezqwBrowser.fillSearchBarText(sel);
			}  
		}
	},


	onUnLoad: function(e) {
		if(_DEBUG) consoleService.logStringMessage("onUnLoad monitor gBrowser unload event ok!");

		//gBrowser.removeEventListener("DOMContentLoaded", function(e) { gBrowserListener.onPageLoad(e); }, true);
		gBrowser.removeEventListener("load", function(e) { gBrowserListener.onLoad(e); }, true);
		gBrowser.removeEventListener("TabOpen", function(e) { gBrowserListener.onTabOpen(e); }, true);
		gBrowser.removeEventListener("TabSelect", function(e) { gBrowserListener.onTabSelect(e); }, true);
		gBrowser.removeEventListener("pageshow", function(e) { gBrowserListener.onPageShow(e); }, true);
		//gBrowser.removeEventListener("pagehide", function(e) { gBrowserListener.onPageShow(e); }, true);
	},

  getPlatform: function() {
        var platform = navigator.platform.toLowerCase();
        if(platform.indexOf('win') != -1) return 'win'; // win
        else if(platform.indexOf('mac') != -1) return 'mac'; // mac
        else return 'other'; // other (nix)
    },

    getEol: function() {
        switch(this.getPlatform()) {
            case 'win': return '\r\n';
            case 'mac': return '\r';
            case 'other': return '\n';
            default: return '<eol>';
        }
    },

	addLinksSignature: function(){

		if(fxf_pref_enablesignature){

			var signature = fxf_pref_signature;

			var alinks, images,scripts,links,a;
			regSignature = signature.replace(/\./g, "\\\.");
			if(_DEBUG) consoleService.logStringMessage("regSignature="+regSignature);

			//process <a
			alinks = window._content.document.evaluate("//a", window._content.document,	null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,	null);
			for (var i = 0; i < alinks.snapshotLength; i++) {
				a = alinks.snapshotItem(i);

				if (a.href && !a.href.match(/[\(\)]/i)){ //not javascript function call e.g. <a href='function()'>
					myRe = new RegExp (regSignature, "g");
					myArray = myRe.exec(a.href);
					if (myRe.lastIndex < 1 )	{
						if (a.href.match(/[\?]/i)) signature = '&' + fxf_pref_signature;  else signature = '?' + fxf_pref_signature;
						if (a.href.match(/[#]/i)) a.href = a.href.replace("#",signature+"#"); else a.href += signature;
					}
				}
			}

			//process <img
			images = window._content.document.evaluate("//img", window._content.document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
			for (var i = 0; i < images.snapshotLength; i++) {
				a = images.snapshotItem(i);
				if (a.src && !a.src.match(/[\(\)]/i)){ //not javascript function call e.g. <IMG src='function()'>
					myRe = new RegExp (regSignature, "g");
					myArray = myRe.exec(a.src);
					if (myRe.lastIndex < 1)	{
						if (a.src.match(/[\?]/i)) signature = '&' + fxf_pref_signature;  else signature = '?' + fxf_pref_signature;
						if (a.src.match(/[#]/i)) a.src = a.src.replace("#",signature+"#"); else a.src += signature;
					}
				}
			}

			//process <script
			scripts = window._content.document.evaluate("//script",window._content.document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,	null);
			for (var i = 0; i < scripts.snapshotLength; i++) {
				a = scripts.snapshotItem(i);
				if (a.src && !a.src.match(/[\(\)]/i)){ //not javascript function call e.g. <a href='function()'>
					myRe = new RegExp (regSignature, "g");
					myArray = myRe.exec(a.src);
					if (myRe.lastIndex < 1)	{
						if (a.src.match(/[\?]/i)) signature = '&' + fxf_pref_signature;  else signature = '?' + fxf_pref_signature;
						if (a.src.match(/[#]/i)) a.src = a.src.replace("#",signature+"#"); else a.src += signature;
					}
				}
			}

			//process <link
			links = window._content.document.evaluate("//link",window._content.document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,	null);
			for (var i = 0; i < links.snapshotLength; i++) {
				a = links.snapshotItem(i);
				if (a.href && !a.href.match(/[\(\)]/i)){ //not javascript function call e.g. <a href='function()'>
					myRe = new RegExp (regSignature, "g");
					myArray = myRe.exec(a.href);
					if (myRe.lastIndex < 1)	{
						if (a.href.match(/[\?]/i)) signature = '&' + fxf_pref_signature;  else signature = '?' + fxf_pref_signature;
						if (a.href.match(/[#]/i)) a.href = a.href.replace("#",signature+"#"); else a.href += signature;
					}
				}
			}
		}
	},


	//refer to https://addons.mozilla.org/zh-CN/firefox/addon/383
	_autocopy_getSelection: function () 
	{
		var SelectionText = "";
		var trywindow = false;
		var focusedElement = document.commandDispatcher.focusedElement;
		if(focusedElement && null != focusedElement){
		  try{
			SelectionText = focusedElement.value.substring(focusedElement.selectionStart, focusedElement.selectionEnd);
		  }catch(e){
			trywindow = true;
		  }
		}else{
		  trywindow = true;
		}

		if(trywindow){
		  var focusedWindow = document.commandDispatcher.focusedWindow;
		  try{
			var winWrapper = new XPCNativeWrapper(focusedWindow, 'document', 'getSelection()');
			var Selection = winWrapper.getSelection();
		  }catch(e){
			var Selection = focusedWindow.getSelection();
		  }
		  SelectionText = Selection.toString();

		}
		return SelectionText;
	} ,

	getKeywords: function ()
	{
		metas = window._content.document.evaluate("/html/head/meta",window._content.document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,	null);
		for (var i = 0; i < metas.snapshotLength; i++) {
			meta = metas.snapshotItem(i);
			if(_DEBUG) consoleService.logStringMessage("getKeywords meta.name="+meta.name);
			if(meta.name && meta.name.toLowerCase() == 'keywords'){
				return meta.content;
			}
		}

		//not found keywords,use title instead
		var title = window._content.document.title;

		return title;
	}

};



window.addEventListener("load", function(e) { ezqwBrowser.start(e); }, false);
window.addEventListener("load", function(e) { gBrowserListener.start(e); }, false);
